package com.chen.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chen.dao.pojo.SysUser;
import com.chen.service.LoginService;
import com.chen.util.UserThreadLocal;
import com.chen.vo.ErrorCode;
import com.chen.vo.Result;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;
    private static final List<String> systemPermissions=new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //在执行controller方法之前执行
        //1.需要判断 请求的接口路径 是否为HandlerMethod(controller方法)
        if (!(handler instanceof HandlerMethod)) {
            //handler可能是 RequestResourceHandler springboot程序访问静态资源 默认访问classpath下的static目录
            return true;
        }
        //2.判断token是否为空，如果为空 未登录
        String token = request.getHeader("token");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            String s = JSON.toJSONString(result);
            response.getWriter().print(s);
            return false;
        }
        //3.如果token不为空 ，登录验证loginService checkToken
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //认为是超级管理员，放行全部
        if (sysUser.getRole().equals("root")){
            return true;
        }
        //此路径下需要root权限，由于上面已经判断了是否超级管理员，到这如果是这个接口就直接返回无权限,个人修改密码权限放行
        if (requestURI.startsWith("/api/sysUser") && !requestURI.startsWith("/api/sysUser/personal")){
            Result result = Result.fail(ErrorCode.NO_PERMISSION.getCode(), ErrorCode.NO_PERMISSION.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //管理会员的权限需要系统管理员
        if (requestURI.startsWith("/api/user")){
            if (sysUser.getRole().equals("system")){
                return true;
            }else {
                Result result = Result.fail(ErrorCode.NO_PERMISSION.getCode(), ErrorCode.NO_PERMISSION.getMsg());
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
        }
        //4.如果认证成功 放行 并酱用户信息放入threadlocal
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完后删除，不然会有线程泄漏的风险
        UserThreadLocal.remove();
    }
}
